<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Spring Security OAuth2 测试页面</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            line-height: 1.6;
        }
        h1 {
            color: #333;
            border-bottom: 2px solid #333;
            padding-bottom: 10px;
        }
        .container {
            margin-bottom: 30px;
            padding: 20px;
            border-radius: 5px;
            background-color: #f8f9fa;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input[type="text"] {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        button {
            padding: 10px 15px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        button:hover {
            background-color: #45a049;
        }
        .token-section {
            background-color: #e9ecef;
            padding: 15px;
            border-radius: 4px;
            margin-top: 10px;
        }
        .api-buttons {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 20px;
        }
        .api-button {
            flex: 1;
            min-width: 120px;
        }
        .result {
            margin-top: 20px;
            padding: 15px;
            background-color: #e9ecef;
            border-radius: 4px;
            white-space: pre-wrap;
            word-break: break-all;
        }
        .copy-button {
            background-color: #2196F3;
            margin-left: 10px;
        }
        .copy-button:hover {
            background-color: #0b7dda;
        }
        .flow-description {
            background-color: #e3f2fd;
            padding: 15px;
            border-radius: 4px;
            margin-bottom: 20px;
            border-left: 4px solid #2196F3;
        }
    </style>
</head>
<body>
    <h1>Spring Security OAuth2 测试页面</h1>

    <div class="flow-description">
        <h3>授权码授权流程说明</h3>
        <p>1. 点击"获取授权码"按钮，跳转到授权服务器进行认证授权</p>
        <p>2. 在授权服务器页面输入用户名密码并授权</p>
        <p>3. 授权成功后，系统会重定向回此页面并携带授权码</p>
        <p>4. 系统自动使用授权码换取访问令牌</p>
        <p>5. 获取令牌后，可以测试访问不同的API端点</p>
    </div>

    <div class="container">
        <h2>1. 获取授权码与访问令牌</h2>
        <div class="form-group">
            <label for="redirectUri">回调URL:</label>
            <input type="text" id="redirectUri" value="http://127.0.0.1:8085/oauth2/callback" placeholder="回调URL">
        </div>
        <button id="authorizeBtn">获取授权码</button>

        <div class="token-section">
            <h3>令牌信息:</h3>
            <div class="form-group">
                <label for="accessToken">访问令牌:</label>
                <input type="text" id="accessToken" readonly>
                <button class="copy-button" onclick="copyToClipboard('accessToken')">复制</button>
            </div>
            <div class="form-group">
                <label for="refreshToken">刷新令牌:</label>
                <input type="text" id="refreshToken" readonly>
                <button class="copy-button" onclick="copyToClipboard('refreshToken')">复制</button>
            </div>
            <div class="form-group">
                <label for="tokenType">令牌类型:</label>
                <input type="text" id="tokenType" readonly>
            </div>
            <div class="form-group">
                <label for="expiresIn">过期时间(秒):</label>
                <input type="text" id="expiresIn" readonly>
            </div>
        </div>
    </div>

    <div class="container">
        <h2>2. 刷新令牌</h2>
        <button id="refreshTokenBtn">刷新令牌</button>
    </div>

    <div class="container">
        <h2>3. 测试API</h2>
        <div class="api-buttons">
            <button class="api-button" onclick="testApi('/oauth2/api/public/hello', '公共API')">测试公共API</button>
            <button class="api-button" onclick="testApi('/oauth2/api/user/data', '用户API')">测试用户API</button>
            <button class="api-button" onclick="testApi('/oauth2/api/admin/dashboard', '管理员API')">测试管理员API</button>
        </div>
        
        <div class="result">
            <h3>API 响应结果:</h3>
            <pre id="apiResult"></pre>
        </div>
    </div>

    <script>
        // 授权参数
        const clientId = 'client-app';
        const clientSecret = 'client-secret';
        const scope = 'read write openid';
        
        // 页面加载时检查URL中是否有授权码
        document.addEventListener('DOMContentLoaded', function() {
            checkForAuthorizationCode();
        });
        
        // 检查URL中是否有授权码
        function checkForAuthorizationCode() {
            const urlParams = new URLSearchParams(window.location.search);
            const code = urlParams.get('code');
            const state = urlParams.get('state');
            
            if (code) {
                document.getElementById('apiResult').textContent = '检测到授权码，正在换取访问令牌...';
                exchangeCodeForToken(code);
            }
        }
        
        // 获取授权码按钮点击事件
        document.getElementById('authorizeBtn').addEventListener('click', function() {
            const redirectUri = document.getElementById('redirectUri').value;
            const state = generateState();
            
            // 保存状态到localStorage，用于验证回调
            localStorage.setItem('oauth_state', state);
            
            // 构建授权请求URL
            const authorizeUrl = '/oauth2/oauth/authorize?response_type=code&client_id=' + clientId + 
                               '&redirect_uri=' + encodeURIComponent(redirectUri) + 
                               '&scope=' + encodeURIComponent(scope) + 
                               '&state=' + state;
            
            // 重定向到授权端点
            window.location.href = authorizeUrl;
        });
        
        // 使用授权码换取访问令牌
        function exchangeCodeForToken(code) {
            const redirectUri = document.getElementById('redirectUri').value;
            
            // 构建请求参数
            const params = new URLSearchParams();
            params.append('grant_type', 'authorization_code');
            params.append('code', code);
            params.append('redirect_uri', redirectUri);
            params.append('scope', scope);
            
            // 发送请求获取令牌
            fetch('/oauth2/oauth/token', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Authorization': 'Basic ' + btoa(clientId + ':' + clientSecret)
                },
                body: params
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('获取令牌失败: ' + response.status);
                }
                return response.json();
            })
            .then(data => {
                // 显示令牌信息
                document.getElementById('accessToken').value = data.access_token;
                document.getElementById('refreshToken').value = data.refresh_token;
                document.getElementById('tokenType').value = data.token_type;
                document.getElementById('expiresIn').value = data.expires_in;
                
                // 显示结果
                document.getElementById('apiResult').textContent = JSON.stringify(data, null, 2);
                
                // 清理URL中的授权码和状态参数
                window.history.replaceState({}, document.title, window.location.pathname);
            })
            .catch(error => {
                document.getElementById('apiResult').textContent = '错误: ' + error.message;
            });
        }
        
        // 刷新令牌按钮点击事件
        document.getElementById('refreshTokenBtn').addEventListener('click', function() {
            const refreshToken = document.getElementById('refreshToken').value;
            
            if (!refreshToken) {
                document.getElementById('apiResult').textContent = '错误: 请先获取令牌';
                return;
            }
            
            // 构建请求参数
            const params = new URLSearchParams();
            params.append('grant_type', 'refresh_token');
            params.append('refresh_token', refreshToken);
            params.append('scope', scope);
            
            // 发送请求刷新令牌
            fetch('/oauth2/oauth/token', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Authorization': 'Basic ' + btoa(clientId + ':' + clientSecret)
                },
                body: params
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('刷新令牌失败: ' + response.status);
                }
                return response.json();
            })
            .then(data => {
                // 更新令牌信息
                document.getElementById('accessToken').value = data.access_token;
                document.getElementById('refreshToken').value = data.refresh_token || refreshToken;
                document.getElementById('tokenType').value = data.token_type;
                document.getElementById('expiresIn').value = data.expires_in;
                
                // 显示结果
                document.getElementById('apiResult').textContent = JSON.stringify(data, null, 2);
            })
            .catch(error => {
                document.getElementById('apiResult').textContent = '错误: ' + error.message;
            });
        });
        
        // 测试API函数
        function testApi(url, apiName) {
            const accessToken = document.getElementById('accessToken').value;
            const tokenType = document.getElementById('tokenType').value;
            
            if (!accessToken) {
                document.getElementById('apiResult').textContent = '错误: 请先获取令牌';
                return;
            }
            
            // 发送请求测试API
            fetch(url, {
                method: 'GET',
                headers: {
                    'Authorization': tokenType + ' ' + accessToken
                }
            })
            .then(response => {
                return response.text().then(text => {
                    try {
                        // 尝试解析JSON响应
                        return { status: response.status, body: JSON.parse(text), isJson: true };
                    } catch (e) {
                        // 如果不是JSON，则返回文本
                        return { status: response.status, body: text, isJson: false };
                    }
                });
            })
            .then(data => {
                let resultText = 'API: ' + apiName + '\nURL: ' + url + '\n状态码: ' + data.status + '\n\n响应内容:\n';
                
                if (data.isJson) {
                    resultText += JSON.stringify(data.body, null, 2);
                } else {
                    resultText += data.body;
                }
                
                document.getElementById('apiResult').textContent = resultText;
            })
            .catch(error => {
                document.getElementById('apiResult').textContent = '错误: ' + error.message;
            });
        }
        
        // 生成随机状态参数，防止CSRF攻击
        function generateState() {
            return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
        }
        
        // 复制到剪贴板函数
        function copyToClipboard(elementId) {
            const element = document.getElementById(elementId);
            element.select();
            document.execCommand('copy');
            
            // 显示复制成功提示
            const originalText = element.value;
            element.value = '已复制到剪贴板!';
            setTimeout(() => {
                element.value = originalText;
            }, 2000);
        }
    </script>
</body>
</html>